//
//  ZoomingViewController.m
//  OCDemo
//
//  Created by 李含文 on 2021/5/12.
//

#import "ZoomingViewController.h"

@interface ZoomingViewController ()
@property (weak, nonatomic) IBOutlet UIImageView *image_1;

@property (weak, nonatomic) IBOutlet UIImageView *image_2;
@end

@implementation ZoomingViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
}

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    self.image_2.image = [self zoomingWithScale:15];
}

- (UIImage *)zoomingWithScale:(double)scale {
//    NSData *imgData = UIImageJPEGRepresentation(self.image_1.image, scale);
    NSData *imgData = [self reSizeImageData:self.image_1.image maxImageSize:0 maxSizeWithKB:0];
    UIImage *image = [UIImage imageWithData:imgData];
    CGSize imageSize = self.image_1.image.size;
    CGFloat targetWidth = imageSize.width*scale;
    CGFloat targetHeight = imageSize.height*scale;
    
    UIGraphicsBeginImageContext(CGSizeMake(targetWidth, targetHeight));
    [image drawInRect:CGRectMake(0, 0, targetWidth, targetHeight)];
    UIImage* newImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return newImage;
}

- (NSData *)reSizeImageData:(UIImage *)sourceImage maxImageSize:(CGFloat)maxImageSize maxSizeWithKB:(CGFloat) maxSize {
    if (maxSize <= 0.0) maxSize = 1024.0;
    
    if (maxImageSize <= 0.0) maxImageSize = 1024.0;
    
    //先调整分辨率
    
    CGSize newSize = CGSizeMake(sourceImage.size.width, sourceImage.size.height);
    
    CGFloat tempHeight = newSize.height / maxImageSize;
    
    CGFloat tempWidth = newSize.width / maxImageSize;
    
    if (tempWidth > 1.0 && tempWidth > tempHeight) {
        newSize = CGSizeMake(sourceImage.size.width / tempWidth, sourceImage.size.height / tempWidth);
        
    }
    
    else if (tempHeight > 1.0 && tempWidth < tempHeight){
        newSize = CGSizeMake(sourceImage.size.width / tempHeight, sourceImage.size.height / tempHeight);
        
    }
    
    UIGraphicsBeginImageContext(newSize);
    
    [sourceImage drawInRect:CGRectMake(0,0,newSize.width,newSize.height)];
    
    UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
    
    UIGraphicsEndImageContext();
    
    //调整大小
    
    NSData *imageData = UIImageJPEGRepresentation(newImage,1.0);
    
    CGFloat sizeOriginKB = imageData.length / 1024.0;
    
    CGFloat resizeRate = 0.9;
    
    while (sizeOriginKB > maxSize && resizeRate > 0.1) {
        imageData = UIImageJPEGRepresentation(newImage,resizeRate);
        
        sizeOriginKB = imageData.length / 1024.0;
        
        resizeRate -= 0.1;
        
    }
    
    return imageData;
    
}
@end
